// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-12-02

package batch

import (
	"encoding/json"
	"gitee.com/gomq/sr"
	"gomq/app"
)

type Request struct {
	DelaySeconds any          `json:"delay_seconds" validate:"omitempty,min=0,max=86400" label:"Delay seconds"`
	Topic        sr.TopicName `json:"topic" validate:"required,min=2,max=30" label:"Topic name"`
	Tag          sr.TopicTag  `json:"tag" validate:"required,min=2,max=60" label:"Topic tag"`
	Messages     []any        `json:"messages" label:"Message content" desc:"Accept json or xml"`

	MessageBodies []string `json:"-" validate:"required,min=1,max=100" label:"Message content"`
}

func (o *Request) BeforeValidate() (err error) {
	// Reset delay seconds.
	o.DelaySeconds = app.AnyInt(o.DelaySeconds, 0)

	if o.MessageBodies == nil {
		o.MessageBodies = make([]string, 0)
	}

	for _, v := range o.Messages {
		switch v.(type) {
		case string:
			if s := v.(string); s != "" {
				o.MessageBodies = append(o.MessageBodies, s)
			}
		default:
			if v != nil {
				if buf, be := json.Marshal(v); be == nil {
					if s := string(buf); s != "" {
						o.MessageBodies = append(o.MessageBodies, s)
					}
				}
			}
		}
	}
	return
}
